<template>
	<view class="feedback-container">
		<!-- 页面标题 -->
		<view class="header">
			<text class="title">意见反馈</text>
			<view class="history-btn" @click="goToHistory">
				<u-icon name="list" size="20" color="#1BBC9B"></u-icon>
				<text class="history-text">历史反馈</text>
			</view>
		</view>

		<!-- 反馈表单 -->
		<view class="feedback-form">
			<!-- 反馈类型选择 -->
			<view class="form-item">
				<view class="type-selector" @click="showTypePicker">
					<text v-if="!selectedType" class="form-label">请选择反馈类型</text>
					<text v-else class="selected-text">{{ selectedType }}</text>
					<u-icon name="arrow-down" size="16" color="#999"></u-icon>
				</view>
			</view>

			<!-- 手机号输入 -->
			<view class="form-item">
				<view class="input-wrapper">
					<u-input
						v-model="phoneNumber"
						placeholder="请输入手机号, 方便我们联系你"
						type="number"
						maxlength="11"
						:border="none"
						@blur="validatePhone"
					></u-input>
				</view>
				<view v-if="phoneError" class="error-tip">{{ phoneError }}</view>
			</view>

			<!-- 意见内容输入 -->
			<view class="form-item">
				<view class="form-label">对我们的商品、服务、APP有什么建议或意见，请在这里告诉我们...</view>
				<view class="textarea-wrapper">
					<u-textarea
						v-model="feedbackContent"
						placeholder="请输入您的意见或建议"
						maxlength="200"
						:height="200"
						:border="none"
						@input="onContentInput"
					></u-textarea>
					<view class="char-count">{{ contentLength }}/200</view>
				</view>
			</view>

			<!-- 图片上传 -->
			<view class="form-item">
				<view class="form-label">上传图片 (最多4张)</view>
				<view class="image-upload">
					<view class="image-item" v-for="(image, index) in uploadedImages" :key="index">
						<image :src="image" class="preview-image" mode="aspectFill"></image>
						<view class="delete-btn" @click="deleteImage(index)">
							<u-icon name="close" size="12" color="#fff"></u-icon>
						</view>
					</view>
					<view class="upload-btn" v-if="uploadedImages.length < 4" @click="chooseImage">
						<u-icon name="plus" size="30" color="#999"></u-icon>
					</view>
				</view>
			</view>
		</view>

		<!-- 提交按钮 -->
		<view class="submit-section">
			<u-button 
				type="primary" 
				:custom-style="submitButtonStyle"
				@click="submitFeedback"
				:disabled="!canSubmit"
			>
				提交
			</u-button>
		</view>

		<!-- 反馈类型选择器 -->
		<u-action-sheet
			:show="showTypeActionSheet"
			:actions="feedbackTypes"
			@close="showTypeActionSheet = false"
			@select="selectFeedbackType"
			title="请选择反馈类型"
			cancel-text="取消"
		></u-action-sheet>
	</view>
</template>

<script>
	import { get, post } from "@/utils/request"; 
	
	export default {
		data() {
			return {
				selectedType: '',
				showTypeActionSheet: false,
				feedbackTypes: [
					{ name: '商品相关' },
					{ name: '订单支付' },
					{ name: '账户积分' },
					{ name: '优惠活动' },
					{ name: '产品建议' },
					{ name: '其他' }
				],
				phoneNumber: '',
				phoneError: '',
				feedbackContent: '',
				contentLength: 0,
				uploadedImages: [],
				submitButtonStyle: {
					backgroundColor: '#1BBC9B',
					color: '#fff',
					borderRadius: '12rpx',
					fontSize: '32rpx',
					height: '88rpx',
					lineHeight: '88rpx',
					fontWeight: 'bold'
				}
			}
		},
		computed: {
			canSubmit() {
				return this.selectedType && 
					   this.phoneNumber && 
					   !this.phoneError && 
					   this.feedbackContent.trim();
			}
		},
		methods: {
			goToHistory() {
				uni.navigateTo({
					url: '/pages/mySxz/feedback/feedbackHistory'
				});
			},
			showTypePicker() {
				this.showTypeActionSheet = true;
			},
			selectFeedbackType(e) {
				this.selectedType = e.name;
				this.showTypeActionSheet = false;
			},
			validatePhone() {
				const phoneRegex = /^1[3-9]\d{9}$/;
				if (!this.phoneNumber) {
					this.phoneError = '请输入手机号';
				} else if (!phoneRegex.test(this.phoneNumber)) {
					this.phoneError = '请输入正确的手机号格式';
				} else {
					this.phoneError = '';
				}
			},
			onContentInput(value) {
				this.contentLength = value.length;
			},
			chooseImage() {
				uni.chooseImage({
					count: 4 - this.uploadedImages.length,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						res.tempFilePaths.forEach(path => {
							if (this.uploadedImages.length < 4) {
								this.uploadImage(path);
							}
						});
					},
					fail: (err) => {
						console.log('选择图片失败', err);
						uni.showToast({
							title: '选择图片失败',
							icon: 'none'
						});
					}
				});
			},
		async uploadImage(filePath) {
		  try {
		    uni.showLoading({ title: '上传中...' });
		
		    // 从缓存获取 token
		    const token = uni.getStorageSync("token") || "";
		
		    const result = await new Promise((resolve, reject) => {
		      uni.uploadFile({
		        url: 'http://localhost:85/dev-api/file/upload',
		        filePath: filePath,
		        name: 'file',
		        header: {
		          Authorization: token, // 如果你的接口是 Bearer token
		          // 或者自定义 header，比如 'token': token
		        },
		        success: (res) => {
		          try {
		            const data = JSON.parse(res.data);
		            if (data.code === 200 && data.data) {
		              resolve(data.data.url); // 返回图片URL而不是整个data对象
		            } else {
		              reject(new Error(data.msg || '上传失败'));
		            }
		          } catch (err) {
		            reject(err);
		          }
		        },
		        fail: (err) => {
		          reject(err);
		        }
		      });
		    });
		
		    uni.hideLoading();
		    this.uploadedImages.push(result);
		
		    uni.showToast({
		      title: '上传成功',
		      icon: 'success'
		    });
		  } catch (error) {
		    uni.hideLoading();
		    console.error('图片上传失败:', error);
		    uni.showToast({
		      title: '图片上传失败',
		      icon: 'none'
		    });
		  }
		},
			deleteImage(index) {
				this.uploadedImages.splice(index, 1);
			},
			async submitFeedback() {
				if (!this.canSubmit) {
					uni.showToast({
						title: '请完善反馈信息',
						icon: 'none'
					});
					return;
				}

				try {
					const membersId = uni.getStorageSync("userId"); 
					if (!membersId) {
						uni.showToast({
							title: '用户未登录',
							icon: 'none'
						});
						return;
					}

					const imageUrls = this.uploadedImages.join(",");
					const payload = {
						createTime: null,
						delFlag: "0",
						description: this.feedbackContent,
						feedbackType: this.feedbackTypes.findIndex(t => t.name === this.selectedType),
						id: null,
						imageUrls: imageUrls,
						membersId: membersId,
						reply: null,
						status: 0,
						storeInfoId: 1,
						updateTime: null
					};

					uni.showLoading({ title: "提交中..." });
					await post("/transaction/YZMfeedback", payload);
					uni.hideLoading();

					uni.showToast({
						title: '提交成功',
						icon: 'success'
					});

					this.resetForm();
				} catch (err) {
					uni.hideLoading();
					console.error("提交失败", err);
					uni.showToast({
						title: '提交失败，请稍后重试',
						icon: 'none'
					});
				}
			},
			resetForm() {
				this.selectedType = '';
				this.phoneNumber = '';
				this.phoneError = '';
				this.feedbackContent = '';
				this.contentLength = 0;
				this.uploadedImages = [];
			}
		}
	}
</script>

<style lang="scss" scoped>
	.feedback-container {
		background-color: #f5f5f5;
		min-height: 100vh;
		padding-bottom: 120rpx;
	}
	
	.header {
		background-color: #fff;
		padding: 30rpx 40rpx;
		border-bottom: 1rpx solid #eee;
		display: flex;
		justify-content: space-between;
		align-items: center;
		
		.title {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
		}

		.history-btn {
			display: flex;
			align-items: center;
			padding: 10rpx 20rpx;
			background-color: #f8f9fa;
			border-radius: 20rpx;
			cursor: pointer;

			.history-text {
				font-size: 24rpx;
				color: #1BBC9B;
				margin-left: 8rpx;
			}
		}
	}
	
	.feedback-form {
		background-color: #fff;
		margin-top: 20rpx;
	}
	
	.form-item {
		padding: 30rpx 40rpx;
		border-bottom: 1rpx solid #f0f0f0;
		
		&:last-child {
			border-bottom: none;
		}
		
		.form-label {
			font-size: 28rpx;
			color: #333;
			margin-bottom: 20rpx;
			line-height: 1.5;
		}
	}
	
	.type-selector {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #eee;
		
		.selected-text {
			font-size: 28rpx;
			color: #333;
			
			&.placeholder {
				color: #999;
			}
		}
	}
	
	.input-wrapper {
		border-bottom: 1rpx solid #eee;
		padding: 20rpx 0;
	}
	
	.error-tip {
		font-size: 24rpx;
		color: #ff4757;
		margin-top: 10rpx;
	}
	
	.textarea-wrapper {
		position: relative;
		border: 1rpx solid #eee;
		border-radius: 8rpx;
		padding: 20rpx;
		background-color: #fafafa;
		
		.char-count {
			position: absolute;
			bottom: 10rpx;
			right: 20rpx;
			font-size: 24rpx;
			color: #999;
		}
	}
	
	.image-upload {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
		margin-top: 20rpx;
	}
	
	.image-item {
		position: relative;
		width: 160rpx;
		height: 160rpx;
		border-radius: 8rpx;
		overflow: hidden;
		
		.preview-image {
			width: 100%;
			height: 100%;
		}
		
		.delete-btn {
			position: absolute;
			top: 10rpx;
			right: 10rpx;
			width: 40rpx;
			height: 40rpx;
			background-color: rgba(0, 0, 0, 0.6);
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}
	
	.upload-btn {
		width: 160rpx;
		height: 160rpx;
		border: 2rpx dashed #ddd;
		border-radius: 8rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #fafafa;
		cursor: pointer;
		
		&:active {
			background-color: #f0f0f0;
		}
	}
	
	.submit-section {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		padding: 20rpx 40rpx;
		border-top: 1rpx solid #eee;
		z-index: 100;
	}
</style>
